package wqldistinctlocktest.distinctlock.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wqldistinctlocktest.distinctlock.dao.StockDao;
import wqldistinctlocktest.distinctlock.entity.Stock;
import wqldistinctlocktest.distinctlock.service.StockService_syn;

/**
 * @author wql
 * @version 1.0
 * @date 2022/12/8 16:56
 */
@Service
public class StockService_synImpl implements StockService_syn {
    @Autowired
    private StockDao stockDao;

    @Override
    public String decrement(Integer productid) {
        synchronized (StockService_syn.class.getClassLoader()) {
            //1. 查找指定商品的库存
            Stock stock = stockDao.selectById(productid);
            //2. 判断库存数是否大于0
            if (stock.getStock() > 0) {
                //3.减库存
                stock.setStock(stock.getStock() - 1);
                stockDao.updateById(stock);
                System.out.println("商品编号为:" + productid + "的商品库存剩余:" + stock.getStock() + "个");
                return "商品编号为:" + productid + "的商品库存剩余:" + stock.getStock() + "个";
            } else {
                System.out.println("商品编号为:" + productid + "的商品库存不足。");
                return "商品编号为:" + productid + "的商品库存不足。";
            }
        }
    }
}
